package com.example.excelimporter.service.impl;

import com.example.excelimporter.model.ErrorRecord;
import com.example.excelimporter.service.DataSaveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class DataSaveServiceImpl implements DataSaveService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    @Transactional
    public void saveValidData(Object data, String targetTable) {
        // TODO: 实现有效数据的保存逻辑
        // 1. 根据目标表名动态生成SQL
        // 2. 将数据插入目标表
    }

    @Override
    @Transactional
    public void saveInvalidData(Object data, String errorMessage, String targetTable) {
        // 保存错误记录
        ErrorRecord errorRecord = new ErrorRecord();
        errorRecord.setTemplateId("1"); // TODO: 获取实际模板ID
        errorRecord.setRowNumber(1); // TODO: 获取实际行号
        errorRecord.setFieldName(""); // TODO: 获取实际字段名
        errorRecord.setErrorMessage(errorMessage);
        errorRecord.setRawValue(data.toString());

        String sql = "INSERT INTO error_records (template_id, row_number, field_name, error_message, raw_value) " +
                     "VALUES (?, ?, ?, ?, ?)";
        jdbcTemplate.update(sql,
                errorRecord.getTemplateId(),
                errorRecord.getRowNumber(),
                errorRecord.getFieldName(),
                errorRecord.getErrorMessage(),
                errorRecord.getRawValue());
    }
}
